/**
 * All rights reserved by www.xmerge.cn
 */
package net.xfok.xmerge;

import java.io.InputStream;
import java.util.List;

import net.xfok.rss.parser.Feed;
import net.xfok.xmerge.manage.RssManage;
import net.xfok.xmerge.parser.RssParser;
import net.xfok.xmerge.provider.RssItem;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.AdapterView.OnItemClickListener;


/**
 * @author YangHua
 *
 */
public class ImportList extends Activity implements OnItemClickListener,OnClickListener{
	private static final String TAG = "ImportList";
	private static final String RSS_FILE="rsses.xml";
	private ArrayAdapter<RssItem> importAdapter=null;
	private ListView importList;
	private Button btBack;
	private RelativeLayout mContainer;
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.imports);
        mContainer=(RelativeLayout)findViewById(R.id.i_container);
        importList=(ListView)findViewById(R.id.import_list);
        btBack=(Button)findViewById(R.id.i_bt_back);
        btBack.setOnClickListener(this);
        importList.setOnItemClickListener(this);
//        if(RssManage.checkNet(this)){
    	try{
    		showList(); 
    	}catch(Exception e){
    		e.printStackTrace();
    		finish();
    	}
//        }
//		else{
//        	finish();
//        }       
    }
	
	private void showList(){
		importAdapter= new ArrayAdapter<RssItem>(this,android.R.layout.simple_list_item_multiple_choice); 
		try{
			InputStream is=getAssets().open(RSS_FILE);
			RssParser parser=new RssParser(is);
			List<RssItem> rssItems=parser.getRssItems();
			if(RssManage.checkNet(this)){
				String url=getResources().getText(R.string.import_url).toString();
				Log.i(TAG, "Import url : "+url);
				parser=new RssParser(url);
				rssItems=parser.getRssItems();
			}
			for(RssItem rssItem:rssItems){
				importAdapter.add(rssItem);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
        importList.setAdapter(importAdapter);  
        importList.setItemsCanFocus(false);
        importList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
	}
	 
	 private void addRssItem(){	 
		 SparseBooleanArray cips=importList.getCheckedItemPositions();
		 Log.i(TAG, "size:"+cips.size());
		 for(int i=0;i<cips.size();i++){
			 int key=cips.keyAt(i);
			 Log.i(TAG,"key="+key);
			 RssItem rssItem=(RssItem)importList.getAdapter().getItem(key);	
			 if(cips.get(key)){
				 if(!rssIsExit(rssItem)){
					 RssManage.addRssItem(rssItem,this); 
				 }
			 }
		 }
	 }
	 
	 private boolean rssIsExit(RssItem rssItem){
		 boolean result=false;
		 Uri rssUrl = RssItem.Rss.CONTENT_URI;
		 String selection=RssItem.Rss.RSS_COLUMN_URL+" like '"+rssItem.getUrl()+"'";
	     Cursor cur = managedQuery(rssUrl, RssItem.Rss.COLUMNS , selection, null, null );
	     if(cur.getCount()>0){
	    	 result=true;
	     }
	     return result;
	 }

	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		 Log.i(TAG, "position="+position);
		 RssItem rssItem=(RssItem)importList.getAdapter().getItem(position);		
		 Log.i(TAG, rssItem.toString());
		 addRssItem();
	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.i_bt_back:
			applyRotation(0, 0, 90);
			break;
		default:
			break;
		}
	}
	
    private void applyRotation(int position, float start, float end) {
        // Find the center of the container
        final float centerX = mContainer.getWidth() / 2.0f;
        final float centerY = mContainer.getHeight() / 2.0f;

        // Create a new 3D rotation with the supplied parameter
        // The animation listener is used to trigger the next animation
        final Rotate3dAnimation rotation =
                new Rotate3dAnimation(start, end, centerX, centerY, 310.0f, true);
        rotation.setDuration(500);
        rotation.setFillAfter(true);
        rotation.setInterpolator(new AccelerateInterpolator());
        rotation.setAnimationListener(new DisplayNextView(position));

        mContainer.startAnimation(rotation);
    }
    
    private final class SwapViews implements Runnable {
        private final int mPosition;

        public SwapViews(int position) {
            mPosition = position;
        }
        public void run() {
            final float centerX = mContainer.getWidth() / 2.0f;
            final float centerY = mContainer.getHeight() / 2.0f;
            Rotate3dAnimation rotation; 
            Intent intent=new Intent(ImportList.this,RssList.class);
			startActivity(intent);
			finish();
            rotation = new Rotate3dAnimation(90, 360, centerX, centerY, 310.0f, false);
            rotation.setDuration(500);
            rotation.setFillAfter(true);
            rotation.setInterpolator(new DecelerateInterpolator());
            mContainer.startAnimation(rotation);
        }
    }
    
    
    private final class DisplayNextView implements Animation.AnimationListener {
        private final int mPosition;

        private DisplayNextView(int position) {
            mPosition = position;
        }

        public void onAnimationStart(Animation animation) {
        }

        public void onAnimationEnd(Animation animation) {
            mContainer.post(new SwapViews(mPosition));
        }

        public void onAnimationRepeat(Animation animation) {
        }
    }
	  
}
